/*
 * Created on 2008-8-20
 *
 * TODO
 */
package jacky.lanlan.song.pattern.factory;

import java.lang.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 读取Properties文件的配置值的 {@code AnnotationFactory}。读取的配置文件会被缓存。
 * 
 * @see PatternUtils#loadPropertyFromAnnotation()
 * @see PropertiesCfg
 * @author Jacky.Song
 */
public class PropertyReadFactory implements PropertyValueGenerator<String[]> {

	// [properties文件路径 => Properties对象]
	private final Map<String, Properties> cache = new HashMap<String, Properties>();
	
	private final Lock cacheLock = new ReentrantLock();
	
	public String[] generate(Annotation anno) {
		PropertiesCfg cfg = (PropertiesCfg) anno;
		String filePath = cfg.path();
		cacheLock.lock();
		try {
			if (!cache.containsKey(filePath)) {
				Properties properties = new Properties();
				try {
					properties.load(cfg.classLoader().getResourceAsStream(filePath));
				}
				catch (Exception e) {
					throw new RuntimeException("无法在 [" + cfg.classLoader().getResource("/") + "] 找到 " + filePath);
				}
				cache.put(filePath, properties);
			}
		}
		finally {
			cacheLock.unlock();
		}
		
		String [] keys = cfg.keys();
		String [] values = new String[keys.length];
		for (int i = 0; i < values.length; i++) {
			values[i]=cache.get(filePath).getProperty(keys[i]);
		}
		return values;
	}
	
}
